package com.zhou.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;
@Slf4j
public class PropertyUtil {
    private static final Map<String, Map<String,String>> propertiesMap = new Hashtable<>(1);

    public static String getStringValue(String filePathName,String key,String dv){
        Map<String,String> p = propertiesMap.computeIfAbsent(filePathName,o->loadProperties(filePathName,"GBK"));
        return MapUtils.getString(p,key,dv);
    }
    public static Integer getIntegerValue(String filePathName,String key,Integer dv){
        Map<String,String> p = propertiesMap.computeIfAbsent(filePathName,o->loadProperties(filePathName,"GBK"));
        return MapUtils.getInteger(p,key,dv);
    }
    public static Boolean getBooleanValue(String filePathName,String key,Boolean dv){
        Map<String,String> p = propertiesMap.computeIfAbsent(filePathName,o->loadProperties(filePathName,"GBK"));
        return saveToBoolean(p.get(key),dv);
    }
    public static Map<String,String> getPropertiesMap(String filePathName){
        return propertiesMap.computeIfAbsent(filePathName,o->loadProperties(filePathName,"GBK"));
    }
    public static Properties getProperties(String filePathName,String charset) throws Exception{
        InputStreamReader reader = null;
        InputStream in = null;
        try{
            in = PropertyUtil.class.getClassLoader().getResourceAsStream(filePathName);
            reader = new InputStreamReader(in,charset);
            Properties p = new OrderedProperties();
            p.load(reader);
            return p;
        }finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(in);
        }
    }
    public static Map<String,String> loadProperties(String filePathName,String charset){

        Map<String,String> urlConfig = new LinkedHashMap<>(3);
        try{
            Properties p = getProperties(filePathName,charset);
            for (String key : p.stringPropertyNames()) {
                String value = p.getProperty(key);
                urlConfig.put(key, value);
            }
            return urlConfig;
        }catch (Exception e){
            log.error("",e);
            throw new IllegalArgumentException("Properties load error!");
        }
    }
    public static Boolean saveToBoolean(Object o,Boolean dv){
        try{
            if (o == null) {
                return dv;
            }else if(o instanceof Boolean){
                return (Boolean) o;
            }else if(o instanceof String){
                return Boolean.valueOf((String) o);
            }
            return dv;
        }catch (Exception e){
            return dv;
        }
    }
}
